package com.finance.cooperate.strategy.strategy;

import com.alibaba.fastjson.JSON;
import com.finance.cooperate.common.constant.Constant;
import com.finance.cooperate.common.utils.Jexl3Utils;
import com.finance.cooperate.dao.entity.secondary.StrategyInfo;
import com.finance.cooperate.strategy.core.strategy.AbstractStrategyHandler;
import com.finance.cooperate.strategy.core.strategy.StrategyScope;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName RePrefixRule
 * @Description 这是一个最基本的策略配置，用于匹配 re_* 开头的所有配置
 * @Author shenanxin
 * @Date 2023/9/18 13:19
 * @Modify ...
 */
@Component
@Slf4j
public class RePrefixRule extends AbstractStrategyHandler {

    @Autowired
    private StrategyScope strategyScope;

    @Override
    public Long execute(StrategyInfo strategyInfo) {

        try {

            String featureRule = strategyInfo.getFeatureRule();

            Map<String, String> featureMap = strategyScope.getFeatureMap();

            // 添加一个权重数
            long seed = strategyInfo.getId() * uid.get().hashCode();
            long weight = seed % 100;

            featureMap.put("weight", String.valueOf(Math.abs(weight)));

            // 先获取到所需特征
            List<String> ruleVars = Jexl3Utils.extractVariables(featureRule);

            Map<String, Object> ruleFeature = new HashMap<>();

            for (String var : ruleVars) {
                ruleFeature.put(var, Double.valueOf(String.valueOf(featureMap.getOrDefault(var, String.valueOf(Constant.MISSING_VALUE)))));
            }

            boolean isHit = Jexl3Utils.evaluateCondition(featureRule, ruleFeature);

            if (isHit) {
                super.hitResult(ruleFeature, strategyInfo);

                return strategyInfo.getId();
            }

        } catch (Exception e) {
            log.error("RePrefixRule 规则错误：", e);
        }

        return null;
    }

    @Override
    public String setStrategyName() {
        return "re_";
    }
}
